const path = require("path");
const multer = require("multer");
const { locahost } = require("../tools/locahost");
const { resData, errMessage } = require("../tools/message");
/**
 * 配置 multer 存储选项
 */
const storage = multer.diskStorage({
	destination: path.join(process.cwd(), "src/uploads"),
	filename: (req, file, cb) => {
		const decodedName = Buffer.from(file.originalname, "latin1").toString(
			"utf8"
		);
		// 生成新文件名，保留原始后缀
		const uniqueName =
			"file-" + Date.now() + path.extname(decodedName) || ".unknown";
		cb(null, uniqueName);
	},
});
const upload = multer({ storage });

/**
 * 上传图片功能
 */
exports.upload = (Router) => {
	Router.post("/upload", upload.single("file"), async (req, res) => {
		if (!req.file) {
			return res.status(400).send("No file uploaded.");
		}
		let url = locahost + `/public/${req.file.filename}`;
		try {
			resData(url, res, "上传");
		} catch (err) {
			errMessage(req, res, err);
		}
	});
};
